// 表单验证函数
function validateForm(formId) {
    const form = document.getElementById(formId);
    let isValid = true;
    const errorMessages = [];
    
    // 获取所有必填字段
    const requiredFields = form.querySelectorAll('[required]');
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            const label = form.querySelector(`label[for="${field.id}"]`);
            errorMessages.push(`${label ? label.textContent : field.name}不能为空`);
            field.classList.add('error');
        } else {
            field.classList.remove('error');
        }
    });
    
    // 显示错误信息
    const errorContainer = form.querySelector('.error-container');
    if (errorContainer) {
        if (errorMessages.length > 0) {
            errorContainer.innerHTML = `<div class="message error">${errorMessages.join('<br>')}</div>`;
            errorContainer.style.display = 'block';
        } else {
            errorContainer.style.display = 'none';
        }
    }
    
    return isValid;
}

// 数字验证函数
function validateNumber(value, min = null, max = null) {
    const num = parseInt(value);
    if (isNaN(num)) return false;
    if (min !== null && num < min) return false;
    if (max !== null && num > max) return false;
    return true;
}

// 手机号码验证
function validatePhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
}

// 邮箱验证
function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// 密码强度检查
function checkPasswordStrength(password) {
    let strength = 0;
    
    if (password.length >= 8) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/[a-z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    if (/[^A-Za-z0-9]/.test(password)) strength++;
    
    return strength;
}

// 显示密码强度指示器
function showPasswordStrength(passwordField, strengthElement) {
    const password = passwordField.value;
    const strength = checkPasswordStrength(password);
    
    let message = '';
    let className = '';
    
    switch(strength) {
        case 0:
        case 1:
            message = '弱';
            className = 'weak';
            break;
        case 2:
        case 3:
            message = '中';
            className = 'medium';
            break;
        case 4:
        case 5:
            message = '强';
            className = 'strong';
            break;
    }
    
    if (strengthElement) {
        strengthElement.textContent = message;
        strengthElement.className = className;
    }
}

// 确认删除对话框
function confirmDelete(message = '确定要删除吗？') {
    return confirm(message);
}

// 显示消息提示
function showMessage(message, type = 'success') {
    const messageContainer = document.createElement('div');
    messageContainer.className = `message ${type}`;
    messageContainer.textContent = message;
    
    messageContainer.style.position = 'fixed';
    messageContainer.style.top = '20px';
    messageContainer.style.right = '20px';
    messageContainer.style.zIndex = '1000';
    messageContainer.style.padding = '15px 20px';
    messageContainer.style.borderRadius = '4px';
    messageContainer.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
    messageContainer.style.animation = 'fadeIn 0.5s ease-in-out';
    
    document.body.appendChild(messageContainer);
    
    // 3秒后自动消失
    setTimeout(() => {
        messageContainer.style.opacity = '0';
        messageContainer.style.transition = 'opacity 0.5s';
        setTimeout(() => {
            document.body.removeChild(messageContainer);
        }, 500);
    }, 3000);
}

// 淡入动画
const fadeInKeyframes = `
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-20px); }
    to { opacity: 1; transform: translateY(0); }
}`;

// 添加动画样式
function addAnimationStyles() {
    const styleSheet = document.createElement('style');
    styleSheet.type = 'text/css';
    styleSheet.innerText = fadeInKeyframes;
    document.head.appendChild(styleSheet);
}

// 页面加载完成后执行
window.addEventListener('DOMContentLoaded', function() {
    addAnimationStyles();
    
    // 为所有表单添加验证
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(event) {
            if (this.hasAttribute('data-validate')) {
                if (!validateForm(this.id)) {
                    event.preventDefault();
                }
            }
        });
    });
    
    // 为所有删除按钮添加确认
    const deleteButtons = document.querySelectorAll('.btn-danger');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            if (!confirmDelete()) {
                event.preventDefault();
            }
        });
    });
    
    // 密码强度检查
    const passwordFields = document.querySelectorAll('input[type="password"]');
    passwordFields.forEach(field => {
        field.addEventListener('input', function() {
            const strengthElement = document.getElementById(`${this.id}-strength`);
            if (strengthElement) {
                showPasswordStrength(this, strengthElement);
            }
        });
    });
});

// 平滑滚动
function smoothScroll(targetId) {
    const target = document.getElementById(targetId);
    if (target) {
        target.scrollIntoView({ behavior: 'smooth' });
    }
}

// 页面跳转函数
function redirectTo(url, delay = 0) {
    setTimeout(() => {
        window.location.href = url;
    }, delay);
}

// 获取URL参数
function getURLParameter(name) {
    const param = window.location.search.substring(1)
        .split('&')
        .find(pair => pair.startsWith(name + '='));
    return param ? decodeURIComponent(param.split('=')[1]) : null;
}

// 高亮当前导航项
function highlightCurrentNavItem() {
    const currentPath = window.location.pathname;
    const navItems = document.querySelectorAll('.navbar-menu a');
    
    navItems.forEach(item => {
        if (item.getAttribute('href') === currentPath) {
            item.classList.add('active');
        }
    });
}